package cn.stazxr.controller;

import cn.stazxr.annotation.Log;
import cn.stazxr.entity.YdlLoginUser;
import cn.stazxr.entity.YdlUser;
import cn.stazxr.exception.BusinessException;
import cn.stazxr.service.YdlUserService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.10.29
 **/
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class IndexController {

	private final YdlUserService ydlUserService;

	@Log(title = "用户登录", businessType = "用户操作")
	@PostMapping("/login")
	public ResponseEntity<YdlLoginUser> login(@RequestBody @Validated YdlUser user, BindingResult result) {
		// 1. 处理不合法参数
		List<ObjectError> allErrors = result.getAllErrors();
		allErrors.forEach(error -> log.error("登录时参数校验失败: {}", error.getDefaultMessage()));
		if (!allErrors.isEmpty()) {
			return ResponseEntity.badRequest().build();
		}
		// 2. 执行登录逻辑
		YdlLoginUser ydlLoginUser;
		try {
			ydlLoginUser = ydlUserService.login(user.getUserName(), user.getPassword());
		} catch (BusinessException e) {
			// 登录失败
			log.info(e.getMessage());
			return ResponseEntity.status(e.getCode()).build();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ResponseEntity.internalServerError().build();
		}
		return ResponseEntity.ok().body(ydlLoginUser);
	}

	@Log(title = "用户登出", businessType = "用户操作")
	@PostMapping("/logout")
	public ResponseEntity<String> logout(HttpServletResponse response) {
		try {
			ydlUserService.logout();
			return ResponseEntity.ok().body("success");
		} catch (BusinessException e) {
			log.warn("异常的登出操作");
			response.setStatus(e.getCode());
			return ResponseEntity.status(e.getCode()).body("异常的登出操作");
		}
	}

}
